package handlers

import (
	"github.com/gin-gonic/gin"
	"short-video-mgr/models"
	"strconv"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	context := c.PostForm("context")
	news := models.News{
		Title:   title,
		Context: context,
	}
	err := models.DB.Create(&news).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var news []models.News
	err := models.DB.Offset(offset).Limit(size).Find(&news).Error
	var count int64
	models.DB.Model(&news).Count(&count)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  news,
		"count": count,
	})

}
